﻿using System;
using System.Collections.Generic;
using System.Linq;

using ET;
using Marx;
using Marx.Utils;

namespace Server
{
    [ObjectSystem]
    public class ProcessReadyAwakeSystem : AwakeSystem<ProcessReadyComponent>
    {
        public override void Awake(ProcessReadyComponent self)
        {
            self.Awake();
        }
    }

    public class ProcessReadyComponent : Entity, IAwake
    {
        public static ProcessReadyComponent Instance { get; private set; }

        public class ProcessState
        {
            public StartProcessConfig Config;
            public bool Ready = false;
        }

        private Dictionary<int, ProcessState> states_ = new Dictionary<int, ProcessState>();

        public void Awake()
        {
            Instance = this;

            foreach (var process in StartConfig.Instance.Processes)
            {
                var state = new ProcessState()
                {
                    Config = process,
                    Ready = false
                };
                states_.Add(state.Config.ID, state);
            }
        }

        public void SetReady(int processId)
        {
            var state = states_.GetOrDefault(processId);
            if(state != null)
            {
                state.Ready = true;
            }
            else
            {
                throw new Exception($"Process config Id[{processId}] not found");
            }

            if(states_.All(i => i.Value.Ready))
            {
                Host.Instance.SetHostState(HostState.Running);
            }
        }
    }
}
